package ru.ifmo.auth;

import org.hibernate.Query;
import org.hibernate.Session;
import ru.ifmo.HibernateUtil;
import ru.ifmo.entities.UsersEntity;

import java.util.List;

public class LoginUtils {
    private static LoginUtils instance;

    private final Session session = HibernateUtil.getSession();

    public UsersEntity getAuthUser(final String login, final String password) {
        try {
            final Query query = session.createQuery("from UsersEntity u where u.login = :login");
            query.setString("login", login);
            @SuppressWarnings("unchecked")
            final List<UsersEntity> users = query.list();
            if (users.size() > 1) {
                // oh no, too much users with the same login
                return null;
            } else if (users.size() == 1) {
                // maybe its him?
                final UsersEntity potentialUser = users.get(0);
                final String actualPassword = potentialUser.getPassword();
                if (actualPassword == null) {
                    // hm... this is bad
                    return null;
                } else if (actualPassword.equals(password)) {
                    // yes, this is true user
                    return potentialUser;
                } else {
                    // sorry, wrong password specified
                    return null;
                }
            } else {
                // bad luck, wrong login
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static LoginUtils getInstance() {
        if (instance == null) {
            instance = new LoginUtils();
        }
        return instance;
    }
}
